package dao;

import entity.Pet;
import java.util.Arrays;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

public class PetDAO extends DAO<Pet> {

    public PetDAO(EntityManagerFactory emf) {
        super(emf);
    }

    @Override
    protected Root from(CriteriaQuery cq) {
        return cq.from(Pet.class);
    }

    @Override
    protected boolean exists(Pet object) {
        EntityManager entityManager = getEntityManager();
        Query query = entityManager.createQuery("SELECT p FROM Pet p WHERE p.name=:name AND p.species=:species");
        query.setParameter("name", object.getName());
        query.setParameter("species", object.getSpecies());
        
        return !query.getResultList().isEmpty();
    }
    
    @Override
    public void edit(Pet object) throws Exception {
        EntityManager entityManager = getEntityManager();
        Query query = entityManager.createQuery("DELETE FROM Vaccine v WHERE v.medicalRecord.id = :id");
        query.setParameter("id", object.getMedicalRecord().getId());
        entityManager.getTransaction().begin();
        query.executeUpdate();
        entityManager.getTransaction().commit();
        super.edit(object);
    }
    
    public List findByName(String[] names) {
        EntityManager entityManager = getEntityManager();
        Query query = entityManager.createQuery("SELECT p FROM Pet p where p.name IN :names");
        query.setParameter("names", Arrays.asList(names));
        
        return query.getResultList();
    }

}
